package com.ddyx.common.utils.token;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: AppAuthorizeUtil.java
 * @Description:
 * @author: liuhoujie
 * @date: 2018年6月21日
 */
@Slf4j
public class AppAuthorizeUtil {
	private static ObjectMapper jsonUtil = new ObjectMapper();

	/**
	 * @Description: 获取access_token,refresh_token,openid等重要参数
	 * @return
	 */
	public static Map getAccessTokenByCode(String code) {
		PrintWriter out = null;
		BufferedReader in = null;
		// String result = "";
		Map resultMap = new HashMap<>();
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx8c300ff45db180fb&secret=3e6a7b32cd405344afbaedcc7249337e&code=CODE&grant_type=authorization_code";
		url = url.replace("CODE", code);
		// String param = "";
		// Iterator<String> it = paramMap.keySet().iterator();

		// while(it.hasNext()) {
		// String key = it.next();
		// param += key + "=" + paramMap.get(key) + "&";
		// }

		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			// out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			// out.print(param);
			// flush输出流的缓冲
			// out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			// in = new BufferedReader(new InputStreamReader(conn.getInputStream(),
			// "UTF-8"));
			// String line;
			// while ((line = in.readLine()) != null) {
			// result += line;
			// }
			resultMap = jsonUtil.readValue(conn.getInputStream(), Map.class);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return resultMap;
	}

	/**
	 * @Description: 获取用户个人信息（UnionID机制)
	 * @param accessToken
	 *            调用凭证; openid 普通用户的标识，对当前开发者帐号唯一 lang 国家地区语言版本，zh_CN 简体，zh_TW 繁体，en
	 *            英语，默认为zh-CN(可以不填)
	 * @return
	 */
	public static Map getUserInfo(String accessToken, String openId) {
		PrintWriter out = null;
		BufferedReader in = null;
		Map resultMap = new HashMap<>();
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
		url = url.replace("ACCESS_TOKEN", accessToken);
		url = url.replace("OPENID", openId);
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			resultMap = jsonUtil.readValue(conn.getInputStream(), Map.class);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return resultMap;
	}

}